package cn.yh.register.msm.api;


import cn.yh.register.common.result.Result;
import cn.yh.register.common.util.RandomUtil;
import cn.yh.register.msm.service.MsmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api(tags = "短信服务接口")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation("发送验证码")
    @GetMapping("/send/{phone}")
    public Result<?> sendCode(@PathVariable String phone){

        //从redis中查一下，看code是否过期了，没过期还能用 直接返回OK
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //生成验证码
         code = RandomUtil.getSixBitRandom();
        if (msmService.send(phone,code)){
            //把验证码存入Redis中设置过期时间
            redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("短信发送失败");
        }
    }
}
